package cn.com.b2office.struts2.action;

import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.interceptor.SessionAware;

import cn.com.b2office.domain.Cart;
import cn.com.b2office.domain.Member;
import cn.com.b2office.domain.User;
import cn.com.b2office.service.CartService;
import cn.com.b2office.service.MemberService;
import cn.com.b2office.service.UserService;
import cn.com.b2office.util.DES;
import cn.com.b2office.util.MD5;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author zhenggang
 * @version Jul 7, 2008 11:40:02 AM comment
 */
public class RegisterAction extends ActionSupport implements
		ModelDriven<Member>, SessionAware {
	private static final long serialVersionUID = -1040431911355407401L;

	private static Pattern patternEmail = Pattern
			.compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");

	private Member member = new Member();

	private String confirmPwd;

	private String verifyCodeInput;

	// public static String verifyCode = "";
	private Random random = new Random();

	private String randNum = ""; // 四位随机数字

	private MemberService memberService;

	private DES des = new DES();

	private User user;

	private UserService userService;

	private CartService cartService = null;

	private Map session;

	private String tempPwd;

	@Override
	public String execute() throws Exception {
		tempPwd = member.getRegpwd();
		member.setRegtime(new Date());
		member.setRegpwd(MD5.hash(member.getRegpwd()));
		memberService.createMember(member);
		user = userService.loginByRegName(member.getRegname(), tempPwd); // 注册后登录
		session.put("user", user);
		// 更新购物车
		Cart cart = (Cart) session.get("cart");
		if (cart != null)
			cartService.rebuildCart(cart, user.getMemberId());

		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		// VerifyCode.createVerifyCode(ServletActionContext.getRequest(),
		// ServletActionContext.getResponse());
		// verifyCode = MD5.hash(VerifyCode.sRandCode);

		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			randNum += rand;
		}
		// System.out.println("in RegisterAction, 加密前 randNum = "+randNum);
		//		
		// randNum = des.getEncString(randNum); // 对生成的四位数字进行加密
		// System.out.println("in RegisterAction, 加密后 randNum = "+randNum);
		// randNum = URLEncoder.encode(randNum,"utf-8");
		// System.out.println("URL编码后 "+randNum);
		return INPUT;
	}

	// public String createVerifyCode() throws Exception, IOException {
	//
	// VerifyCode.outPutImage(ServletActionContext.getRequest(),
	// ServletActionContext.getResponse());
	//
	// return NONE;
	// }

	public Member getModel() {
		return member;
	}

	public void validateExecute() {
		if (member.getRegname() == null
				|| member.getRegname().replace(" ", "").equals("")) {
			addFieldError("model.regname", "用户名不能为空");
		} else {
			boolean isChinese = false; // 是否为中文
			for (int i = 0; i < member.getRegname().length(); i++) {
				if (member.getRegname().substring(i, i + 1).matches(
						"[\u4e00-\u9fa5]+")) {
					isChinese = true;
				}
			}
			if (isChinese = false
					|| member.getRegname().replace(" ", "").length() < 5
					|| member.getRegname().replace(" ", "").length() > 20) {
				addFieldError("model.regname", "用户名不符合要求");
			} else if (memberService.ifRegNameExist(member.getRegname()) == true) {
				addFieldError("model.regname", "用户名已经存在");
			}
		}

		if (member.getRegpwd() == null
				|| member.getRegpwd().replace(" ", "").equals("")) {
			addFieldError("model.regpwd", "密码不能为空");
		} else if (member.getRegpwd().replace(" ", "").length() < 6
				|| member.getRegpwd().replace(" ", "").length() > 18) {
			addFieldError("model.regpwd", "密码长度不符合要求");
		}
		if (confirmPwd == null || confirmPwd.replace(" ", "").equals("")) {
			addFieldError("confirmPwd", "请输入确认密码");
		} else if (!member.getRegpwd().equals(confirmPwd)) {
			addFieldError("confirmPwd", "确认密码与密码不同");
		}

		if (member.getRegemail() == null
				|| member.getRegemail().replace(" ", "").equals("")) {
			addFieldError("model.regemail", "email地址不能为空");
		} else {
			Matcher matcher = patternEmail.matcher(member.getRegemail());
			if (matcher.matches() == false) {
				addFieldError("model.regemail", "email地址格式不正确");
			} else if (memberService.ifRegEmailExist(member.getRegemail()) == true) {
				addFieldError("model.regemail", "email地址已经存在");
			}
		}

		if (verifyCodeInput == null
				|| verifyCodeInput.replace(" ", "").equals("")) {
			addFieldError("verifyCodeInput", "请填入验证码");
		} else if (!verifyCodeInput.equals(randNum)) { // 用户输入的验证码与生成的验证码比对
			randNum = "";
			// TODO 校验码需要加密
			for (int i = 0; i < 4; i++) { // 重新生成校验码
				String rand = String.valueOf(random.nextInt(10));
				randNum += rand;
			}

			addFieldError("verifyCodeInput", "验证码不正确");
		}
	}

	public void setConfirmPwd(String confirmPwd) {
		this.confirmPwd = confirmPwd;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	// public String getVerifyCode() {
	// return verifyCode;
	// }

	public void setVerifyCodeInput(String verifyCodeInput) {
		this.verifyCodeInput = verifyCodeInput;
	}

	public String getRandNum() {
		return randNum;
	}

	public void setRandNum(String randNum) {
		this.randNum = randNum;
	}

	public User getUser() {
		return user;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public void setCartService(CartService cartService) {
		this.cartService = cartService;
	}

}
